import Variables from '../others/variables';
import { Lua } from './lua_generator';

export const controls_if = function (a) {
    var b = 0,
        c = "",
        d,
        e;
    do
        e = Lua.valueToCode(a, "IF" + b, Lua.ORDER_NONE) || "false", d = Lua.statementToCode(a, "DO" + b) || Lua.PASS, c += (0 == b ? "if " : "elseif ") + e + " then\n" + d, ++b;
    while (a.getInput("IF" + b));
    a.getInput("ELSE") && (d = Lua.statementToCode(a, "ELSE") || Lua.PASS, c += "else\n" + d);
    return c + "end\n"
};

export const controls_for = function () {
    // For loop.
    var variable0 = Lua.variableDB_.getName(
        this.getFieldValue('VAR'), Variables.NAME_TYPE);
    var argument0 = Lua.valueToCode(this, 'FROM',
        Lua.ORDER_ASSIGNMENT) || '0';
    var argument1 = Lua.valueToCode(this, 'TO',
        Lua.ORDER_ASSIGNMENT) || '0';
    var step = Lua.valueToCode(this, 'STEP',
        Lua.ORDER_ASSIGNMENT) || '1';
    var branch = Lua.statementToCode(this, 'DO');
    if (Lua.INFINITE_LOOP_TRAP) {
        branch = Lua.INFINITE_LOOP_TRAP.replace(/%1/g,
            '\'' + this.id + '\'') + branch;
    }
    var code;
    code = 'for ' + variable0 + ' = ' + argument0 + ', ' + argument1 + ', ' + step + ' do\n' +
        branch + 'end\n';
    return code;
};

export const controls_whileUntil = function (a) {
    var b = "UNTIL" == a.getFieldValue("MODE"),
        c = Lua.valueToCode(a, "BOOL", Lua.ORDER_NONE) || "false",
        d = Lua.statementToCode(a, "DO");
    d = Lua.addLoopTrap(d, a.id) || Lua.PASS;
    b && (c = "not " + c);
    return "while " + c + " do\n" + d + "end\n"
};

export const controls_flow_statements = function (a) {
    switch (a.getFieldValue("FLOW")) {
    case "BREAK":
        return "break\n";
    case "CONTINUE":
        return "continue\n"
    }
    throw "Unknown flow statement.";
};

//do-while循环
export const do_while = function () {
    var value_select_data = Lua.valueToCode(this, 'select_data', Lua.ORDER_NONE) || "false";
    var statements_input_data = Lua.statementToCode(this, 'input_data')
    var dropdown_type = this.getFieldValue('type');
    if (dropdown_type == 'true') {
        statements_input_data = statements_input_data + '    if (' + value_select_data + '):\n' + '        break\n';
    }
    else {
        statements_input_data = statements_input_data + '    if not (' + value_select_data + '):\n' + '        break\n';
    }
    statements_input_data = Lua.addLoopTrap(statements_input_data, this.id) || Lua.PASS;
    //var dropdown_type = this.getFieldValue('type');
    var code = 'while True:\n' + statements_input_data;
    return code;
};